package edu.tjut.tjutcommunity.controller;

import com.alibaba.fastjson.JSON;
import edu.tjut.tjutcommunity.config.MyEndpointConfigure;
import edu.tjut.tjutcommunity.entity.NoticeMessage;
import edu.tjut.tjutcommunity.utils.MessageQueueUtils;
import edu.tjut.tjutcommunity.utils.SessionPool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@ServerEndpoint(value = "/websocket/{stuId}", configurator = MyEndpointConfigure.class)
@Component
public class WebSocketEndPoint {
    //与某个客户端的连接会话，需要他来给客户端发送数据
    private Session session;

    @Autowired
    MessageQueueUtils messageQueueUtils;

    //连接建立成功调用的方法
    @OnOpen
    public void onOpen(Session session, @PathParam("stuId") Integer stuId) {
        //把会话加入连接池中

        //userId通过用户传入，session是系统自动产生
        if (stuId != null) {
            SessionPool.sessions.put(stuId.toString(), session);
        }
    }


    //关闭会话的时候
    @OnClose
    public void onClose(Session session) throws IOException {
        SessionPool.close(session.getId());
        session.close();
    }

    //接收客户端的消息后调用的方法，在这里可以进行各种业务逻辑的操作
    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println(message);
        //心跳检测
        if (message.equalsIgnoreCase("ping")) {
            try {
                Map<String, Object> params = new HashMap<>();
                params.put("msg", "pong");
                session.getBasicRemote().sendText(JSON.toJSONString(params));
            } catch (Exception e) {
                e.printStackTrace();
            }
            return;
        }
        if (message.startsWith("ack:")) {
            String[] info = message.split(":");
            String stuId = info[1];
//            if (info.length > 2) {
//                //按messageId删除消息
//                String[] dest = new String[info.length - 1];
//                System.arraycopy(info, 2, dest, 0, info.length - 2);
//                messageQueueUtils.deleteMessageById(stuId);
//                return;
//            }
            //全部删除
            if (!messageQueueUtils.clearMessageQueue(stuId)) {
                //删除失败
                messageQueueUtils.sendText(stuId, "删除失败");
            }
            return;
        }

        //处理获取通知请求
        if (message.startsWith("message:")) {
            String[] info = message.split(":");
            //要求是 message:学号:messageId
            String stuId = info[1];
            String messageId = null;
            if (info.length > 2) {
                messageId = info[2];
            }
            //获得未读消息
            List<NoticeMessage> messages = messageQueueUtils.readMessage(stuId, messageId);
            if (messages.size() == 0) {
                SessionPool.sendMessage(stuId,"empty");
                return;
            }
            SessionPool.sendMessage(stuId, JSON.toJSONString(Collections.singletonMap("msg", messages)));
        }
    }
    //心跳检测：用于服务器断开后进行感知，感知是否存活
}